/*
 * Copyright 2017 JessYan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.work.pay.jsyl.app.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.text.Html;
import android.widget.EditText;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.danikula.videocache.HttpProxyCacheServer;
import com.jess.arms.mvp.IView;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.work.pay.jsyl.app.MyFileNameGenerator;

/**
 * ================================================
 * 放置便于使用 RxJava 的一些工具类
 * <p>
 * Created by JessYan on 11/10/2016 16:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * ================================================
 */
public class RxUtil {
    private static HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        return proxy == null ? (proxy = newProxy(context)) : proxy;
    }

    private static HttpProxyCacheServer newProxy(Context context) {
        return new HttpProxyCacheServer.Builder(context)
                .maxCacheSize(1024 * 1024 * 1024)       // 1 Gb for cache
                .fileNameGenerator(new MyFileNameGenerator())
                .build();
    }
    private RxUtil() {
    }

    public static <T> ObservableTransformer<T, T> applySchedulers(final IView view) {
        return new ObservableTransformer<T, T>() {
            @Override
            public Observable<T> apply(Observable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(@NonNull Disposable disposable) {
                                view.showLoading();//显示进度条
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doFinally(new Action() {
                            @Override
                            public void run() {
                                view.hideLoading();//隐藏进度条
                            }
                        }).compose(RxLifecycleUtils.bindToLifecycle(view));
            }
        };
    }

    /**
     * 此方法已废弃
     *
     * @param view
     * @param <T>
     * @return
     * @see RxLifecycleUtils 此类可以实现 {@link RxLifecycle} 的所有功能, 使用方法和之前一致
     * @deprecated Use {@link RxLifecycleUtils#bindToLifecycle(IView)} instead
     */
    @Deprecated
    public static <T> LifecycleTransformer<T> bindToLifecycle(IView view) {
        return RxLifecycleUtils.bindToLifecycle(view);
    }

    public static void showTipDialog(Context context, int type, String tip) {
        showTipDialog(context, type, tip, 1500,true);
    }
    public static void showTipDialog(Context context, int type, String tip,boolean cancel) {
        showTipDialog(context, type, tip, 1500,cancel);
    }

    public static void showTipDialog(Context context, int type, String tip, long delay,boolean cancel) {
        QMUITipDialog qmuiTipDialog = new QMUITipDialog.Builder(context)
                .setIconType(type)
                .setTipWord(tip)
                .create(cancel);
        qmuiTipDialog.setCanceledOnTouchOutside(cancel);
        qmuiTipDialog.show();
        try {
            new Handler().postDelayed(qmuiTipDialog::dismiss, delay);
        } catch (Throwable e) {
            qmuiTipDialog = null;
            e.printStackTrace();
        }
    }

    public static QMUITipDialog showLoading(Context context, String message) {
        return new QMUITipDialog
                .Builder(context)
                .setTipWord(message)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .create(false);
    }

    public static int getAutoHeight(Context context, int height) {
        ApplicationInfo applicationInfo;
        PackageManager packageManager = context.getPackageManager();
        try {
            applicationInfo = packageManager.getApplicationInfo(context
                    .getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo == null || applicationInfo.metaData == null
                    || !applicationInfo.metaData.containsKey("design_width")
                    || !applicationInfo.metaData.containsKey("design_height")) {
                return height;
            }
            height = (int) (ArmsUtils.getScreenHeidth(context) * height / ((float) applicationInfo.metaData.getInt("design_height")));
        } catch (PackageManager.NameNotFoundException e) {
        }
        return height;
    }

    public static int getAutoWidth(Context context, int width) {
        ApplicationInfo applicationInfo;
        PackageManager packageManager = context.getPackageManager();
        try {
            applicationInfo = packageManager.getApplicationInfo(context
                    .getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo == null || applicationInfo.metaData == null
                    || !applicationInfo.metaData.containsKey("design_width")
                    || !applicationInfo.metaData.containsKey("design_height")) {
                return width;
            }
            int design_width = applicationInfo.metaData.getInt("design_width");
            width = (int) (ArmsUtils.getScreenWidth(context) * width / ((float) design_width));
        } catch (PackageManager.NameNotFoundException e) {
        }
        return width;


    }

    public static boolean showEditTip(IView view, EditText edit, String message) {
        if (ObjectUtils.isEmpty(edit.getText().toString())) {
            view.showMessage(message);
            return true;
        }
        return false;
    }

    /**
     * 获取利用反射获取类里面的值和名称
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            if (!Modifier.isPrivate(field.getModifiers())) {
                continue;
            }
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    public static void showConfirmDialog(Context context, String message, QMUIDialogAction.ActionListener listener) {
        showConfirmDialog(context, "提示", message, listener);
    }

    public static void showConfirmDialog(Context context, String title, String message, QMUIDialogAction.ActionListener listener) {
        new QMUIDialog.MessageDialogBuilder(context)
                .setTitle(title)
                .setMessage(message)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .addAction("取消", (QMUIDialog dialog, int index) -> dialog.dismiss())
                .addAction(0, "确定", QMUIDialogAction.ACTION_PROP_POSITIVE,
                        (QMUIDialog dialog, int index) -> listener.onClick(dialog, index))
                .create(com.qmuiteam.qmui.R.style.QMUI_Dialog).show();
    }

    public static String fromHtml(String content) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            return Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString();
        } else {
            return Html.fromHtml(content).toString();
        }
    }

    public static int getYear() {
        return Integer.parseInt(TimeUtils.date2String(new Date(), new SimpleDateFormat("yyyy")));
    }

    public static String getDateStr(int date) {
        String strDay = "";
        if (date < 10) {
            strDay = "0" + date;
        }else{
            strDay = "" + date;
        }
        return strDay;
    }


}
